package mvp.hibernate.demo.dao;

import mvp.hibernate.demo.model.Phone;
import mvp.hibernate.demo.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;

import java.util.List;

/**
 * Created by user on 06.07.14.
 */
public class PhoneDao {
    public void savePhone(Phone phone) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.save(phone);
        session.getTransaction().commit();
    }

    public void updatePhone(Phone phone) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.update(phone);
        session.getTransaction().commit();
    }

    public List<Phone> getAllPhones() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Criteria query = session.createCriteria(Phone.class);
        List<Phone> list = query.list();
        session.getTransaction().commit();
        return list;
    }

    public Phone getPhoneById(Long id) {
        Phone phone;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        phone = (Phone) session.get(Phone.class, id);
        session.getTransaction().commit();
        return phone;
    }


}
